package rw;

import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁控制
 */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                myCache.put(Thread.currentThread().getName(),Thread.currentThread().getName());
            },String.valueOf(i)).start();
        }
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                myCache.get(Thread.currentThread().getName());
            },String.valueOf(i)).start();
        }
    }
}

class MyCache{
    private volatile Map<String,Object> map = new HashMap();

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //写入时候只能有一个线程写入
    public void put(String key,String value){
        readWriteLock.writeLock().lock();
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"放入"+key+"-OK");
        readWriteLock.writeLock().unlock();
    }

    //读取的时候，多个线程读取
    public void get(String key){
        readWriteLock.readLock().lock();
        String value = (String) map.get(key);
        System.out.println(Thread.currentThread().getName()+"得到"+value+"-OK");
        readWriteLock.readLock().unlock();
    }
}
